# coding=utf-8
# ☯ Author: ChinaPython
# ☯ Email : chinapython@yeah.net
# ☯ Date  : 2019-10-21
import cv2
import time
import numpy as np
from PIL import Image

from flask import Flask
from flask_cors import *
from flask import jsonify
from flask import request

app = Flask(__name__)
# 跨域设置
CORS(app, supports_credentials=True)
app.config['JSON_AS_ASCII'] = False


# 提交图片
@app.route('/put_img', methods=['post'])
def put_img():
    img = request.files.get('image')
    img.save("./static/image/" + img.filename)
    return jsonify({'uri': 'static/image/{}'.format(img.filename)})


# 裁剪图片
@app.route('/cut_img', methods=['GET'])
def cut_img():
    path, sts = request.args.get('uri'), eval(request.args.get('sts'))
    img = cv2.imread(path)
    mask = np.zeros(img.shape, np.uint8)
    pts = np.array([sts], np.int32).reshape((-1, 1, 2))
    mask = cv2.polylines(mask, [pts], True, (0, 0, 0))
    cv2.fillPoly(mask, [pts], (255, 255, 255))
    masked = cv2.bitwise_and(mask, img)
    Image.fromarray(img)
    array = np.zeros((masked.shape[0], masked.shape[1], 4), np.uint8)
    array[:, :, 0:3] = masked
    array[:, :, 3] = 0
    array[:, :, 3][np.where(array[:, :, 0] > 2)] = 255
    array[:, :, 3][np.where(array[:, :, 1] > 2)] = 255
    array[:, :, 3][np.where(array[:, :, 2] > 2)] = 255
    image = Image.fromarray(array).crop((
        min([x for (x, _) in sts]),
        min([y for (_, y) in sts]),
        max([x for (x, _) in sts]),
        max([y for (_, y) in sts]))
    )
    image.putdata([(255, 255, 255, 0) if item[:3] == (255, 255, 255) else item for item in image.getdata()])
    uri = "static/image/{}.png".format(int(time.time()))
    image.save(uri)
    return jsonify({'uri': uri})


if __name__ == '__main__':
    app.run(
        host='0.0.0.0',
        port=48484,
        debug=True
    )
